<template>
  <div class="exercise-container">
    <h2 class="mb-4">
      已完成练习
    </h2>

    <!-- 筛选区域 -->
    <div class="filter-section mb-4">
      <label>筛选状态：</label>
      <select
        v-model="filterStatus"
        class="filter-dropdown"
      >
        <option value="">
          全部状态
        </option>
        <option value="submitted">
          已提交
        </option>
        <option value="marked">
          已批改
        </option>
      </select>
    </div>

    <!-- 加载状态 -->
    <div
      v-if="loading"
      class="loading"
    >
      加载中...
    </div>

    <!-- 错误提示 -->
    <div
      v-if="error"
      class="error"
    >
      {{ error }}
    </div>

    <div v-else>
      <!-- 练习列表 -->
      <div
        v-if="!currentExercise && filteredExercises.length > 0"
        class="exercise-grid grid gap-4"
      >
        <div
          v-for="item in filteredExercises"
          :key="item.exercise.exerciseId"
          class="exercise-card cursor-pointer transition-all"
        >
          <div class="card-body p-4">
            <div class="flex justify-between items-start mb-3">
              <h5 class="card-title">
                {{ item.exercise.exerciseName }}
              </h5>
              <span
                :class="getStatusBadgeClass(item.studentExercise.state)"
                class="status-badge"
              >
                {{ getStatusText(item.studentExercise.state) }}
              </span>
            </div>
            <p class="card-text">
              总分：{{ item.exercise.exerciseScore || 0 }}分<br>
              <span v-if="item.studentExercise.state === 'marked'">
                得分：{{ item.studentExercise.studentScore || 0 }}分 ({{ calculateScorePercentage(item) }}%)
                <span v-if="item.rank !== undefined">当前排名：第 {{ item.rank }} 名</span>
              </span>
              <span v-else-if="item.studentExercise.state === 'submitted'">
                状态：等待教师批改
              </span>
            </p>
            <div class="mt-4 flex justify-center column-gap-5">
              <button
                class="btn btn-primary mr-2"
                @click="handleExerciseClick(item)"
              >
                查看详情
              </button>
              <!-- 添加导出PDF按钮 -->
              <button
                class="btn btn-primary ml-2"
                @click.stop="exportExerciseReport(item)"
              >
                <i class="fas fa-file-pdf me-1" /> 导出PDF
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 无数据提示 -->
      <div
        v-else-if="!currentExercise && (exercises.length === 0 || filteredExercises.length === 0)"
        class="no-data提示 text-center"
      >
        <i class="fa fa-inbox text-4xl mb-4" />
        <p class="text-lg">
          {{ filterStatus ? `暂无${getStatusText(filterStatus)}的练习` : '暂无已完成的练习' }}
        </p>
        <p class="text-sm mt-2">
          请先完成课程中的练习
        </p>
      </div>

      <!-- 练习详情 -->
      <div
        v-else
        class="mt-8"
      >
        <div v-if="currentExercise.studentExercise.state === 'marked'">
          <ExerciseResult
            :exercise="currentExercise"
            :user-id="userId"
            :course-id="courseId"
            :rank="rank"
            @back="handleBack"
          />
        </div>
        <div v-else>
          <ExerciseEditor
            :exercise="currentExercise"
            @back="handleBack"
            @refresh-list="fetchFinishedExercises"
          />
        </div>
        <button
          type="button"
          class="btn btn-secondary mt-4"
          @click="handleBack"
        >
          <i class="fa fa-chevron-left me-1" /> 返回练习列表
        </button>
      </div>
    </div>

    <!-- 报告预览容器（隐藏） -->
    <div
      id="report-container"
      class="report-container hidden"
    >
      <!-- PDF报告将在这里生成 -->
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import ExerciseResult from './ExerciseResult.vue';
import ExerciseEditor from './ExerciseEditor.vue';
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';

export default {
  components: { ExerciseResult, ExerciseEditor },
  props: {
    userId: { type: String, required: true },
    courseId: { type: String, required: true }
  },
  data() {
    return {
      exercises: [],
      currentExercise: null,
      loading: true,
      error: null,
      filterStatus: '', // 筛选状态：''(全部), 'submitted', 'marked'
    };
  },
  computed: {
    filteredExercises() {
      if (!this.filterStatus) return this.exercises; // 全部状态
      return this.exercises.filter(item => item.studentExercise.state === this.filterStatus);
    }
  },
  mounted() {
    this.fetchFinishedExercises();
  },
  methods: {
    calculateScorePercentage(item) {
      const studentScore = item.studentExercise.studentScore || 0;
      const totalScore = item.exercise.exerciseScore || 0;
      return totalScore > 0 ? Math.round((studentScore / totalScore) * 100) : 0;
    },

    async fetchFinishedExercises() {
      this.loading = true;
      this.error = null;
      try {
        const response = await axios.get('/api/exercises/finished', {
          params: { userId: this.userId, courseId: this.courseId }
        });

        const exercisesWithData = await Promise.all(
            response.data.map(async (exercise) => {
              const studentExerciseRes = await axios.get(`/api/exercises/${exercise.exerciseId}/student-exercises`, {
                params: { userId: this.userId }
              });
              const studentExerciseData = studentExerciseRes.data[0];

              const rankResponse = await axios.post(
                  `/api/exercises/${exercise.exerciseId}/ranking/${this.userId}`,
                  {
                    id: {
                      userId: this.userId,
                      exerciseId: exercise.exerciseId
                    },
                    studentScore: studentExerciseData.studentScore,
                    state: studentExerciseData.state
                  }
              );

              return {
                exercise,
                studentExercise: studentExerciseData,
                rank: rankResponse.data
              };
            })
        );

        this.exercises = exercisesWithData;
      } catch (error) {
        this.error = '加载已完成练习失败，请重试';
        console.error('接口请求失败:', error);
      } finally {
        this.loading = false;
      }
    },

    async handleExerciseClick(item) {
      try {
        const detailResponse = await axios.get(`/api/exercises/${item.exercise.exerciseId}/detail`, {
          params: { userId: this.userId }
        });
        this.currentExercise = detailResponse.data;
      } catch (error) {
        this.error = '获取练习详情失败，请重试';
        console.error('获取详情失败:', error);
      }
    },

    handleBack() {
      this.currentExercise = null;
    },

    getStatusText(state) {
      return {
        submitted: '已提交',
        marked: '已批改'
      }[state] ;
    },

    getStatusBadgeClass(state) {
      return {
        submitted: 'bg-yellow-100 text-yellow-800',
        marked: 'bg-green-100 text-green-800'
      }[state] || 'bg-gray-200 text-gray-600';
    },

    // 导出练习报告方法
    async exportExerciseReport(item) {
      try {
        this.loading = true;
        const detailResponse = await axios.get(`/api/exercises/${item.exercise.exerciseId}/detail`, {
          params: { userId: this.userId }
        });
        const exerciseDetail = detailResponse.data;
        // 在exportExerciseReport方法中添加

        // 添加获取排名的逻辑
        if (exerciseDetail.studentExercise.state === 'marked') {
          try {
            const rankResponse = await axios.post(
                `/api/exercises/${exerciseDetail.exercise.exerciseId}/ranking/${this.userId}`,
                {
                  id: {
                    userId: this.userId,
                    exerciseId: exerciseDetail.exercise.exerciseId
                  },
                  studentScore: exerciseDetail.studentExercise.studentScore,
                  state: exerciseDetail.studentExercise.state
                }
            );
            exerciseDetail.rank = rankResponse.data;
          } catch (error) {
            console.error('获取排名失败:', error);
            exerciseDetail.rank = '--'; // 设置为默认值
          }
        }

        // 生成报告内容
        const reportContainer = document.getElementById('report-container');
        reportContainer.classList.remove('hidden');

        reportContainer.innerHTML = this.generateReportHTML(exerciseDetail);


        // 使用html2canvas生成canvas
        const canvas = await html2canvas(reportContainer, {
          scale: 2,
          useCORS: true,
          allowTaint: true,
          logging: false
        });

        // 使用jsPDF生成PDF
        const imgData = canvas.toDataURL('image/png');
        const pdf = new jsPDF('p', 'mm', 'a4');
        const imgWidth = 190;
        const pageHeight = 297;
        const imgHeight = canvas.height * imgWidth / canvas.width;
        let position = 0;

        pdf.addImage(imgData, 'PNG', 10, 10, imgWidth, imgHeight);
        position -= pageHeight;

        // 如果报告超过一页，添加新页面
        while (position > -imgHeight) {
          pdf.addPage();
          pdf.addImage(imgData, 'PNG', 10, position, imgWidth, imgHeight);
          position -= pageHeight;
        }

        // 下载PDF
        pdf.save(`${exerciseDetail.exercise.exerciseName}_报告.pdf`);
        reportContainer.classList.add('hidden');

      } catch (error) {
        console.error('生成报告失败:', error);
        this.error = '生成报告失败，请重试';
      } finally {
        this.loading = false;
      }
    },

    // 生成报告HTML内容
    generateReportHTML(exerciseDetail) {
      return `
        <div class="report">
          <div class="report-header">
            <div class="report-logo">
              <i class="fas fa-book-reader"></i>
            </div>
            <div class="report-title">
              <h1>${exerciseDetail.exercise.exerciseName} - 练习报告</h1>
              <div class="report-subtitle">课程练习完成情况分析</div>
            </div>
          </div>

          <div class="report-summary">
            <div class="summary-item">
              <div class="summary-label">总分</div>
              <div class="summary-value">${exerciseDetail.exercise.exerciseScore || 0}分</div>
            </div>
            <div class="summary-item">
              <div class="summary-label">状态</div>
              <div class="summary-value status-badge ${this.getStatusBadgeClass(exerciseDetail.studentExercise.state)}">
                ${this.getStatusText(exerciseDetail.studentExercise.state)}
              </div>
            </div>
            ${exerciseDetail.studentExercise.state === 'marked' ? `
              <div class="summary-item">
                <div class="summary-label">得分</div>
                <div class="summary-value score-value">
                  ${exerciseDetail.studentExercise.studentScore || 0}分
                  <span class="score-percent">(${this.calculateScorePercentage(exerciseDetail)}%)</span>
                </div>
              </div>
              <div class="summary-item">
                <div class="summary-label">排名</div>
                <div class="summary-value">第 ${exerciseDetail.rank || '--'} 名</div>
              </div>
            ` : ''}
          </div>

          <div class="report-section">
            <h2><i class="fas fa-calendar-alt"></i> 练习信息</h2>
            <table class="exercise-info">
              <tr>
                <td>开始时间</td>
                <td>${new Date(exerciseDetail.exercise.exerciseStartTime).toLocaleString()}</td>
              </tr>
              <tr>
                <td>截止时间</td>
                <td>${new Date(exerciseDetail.exercise.exerciseDeadline).toLocaleString()}</td>
              </tr>
              <tr>
                <td>允许多次提交</td>
                <td>${exerciseDetail.exercise.isMultipleSubmission ? '是' : '否'}</td>
              </tr>
            </table>
          </div>

         // 修改后的题目详情部分
${exerciseDetail.studentExercise.state === 'marked' && exerciseDetail.questions ? `
  <div class="report-section">
    <h2><i class="fas fa-list-ol"></i> 题目详情</h2>

    ${exerciseDetail.questions.map((item, index) => {
        const question = item.question;  // 从DTO中获取question对象
        const studentAnswer = item.studentAnswer;  // 从DTO中获取studentAnswer对象

        return `
        <div class="question-item ${studentAnswer?.isCorrect ? 'correct' : 'incorrect'}">
          <div class="question-header">
            <span class="question-number">第${index+1}题</span>
            <span class="question-score">${studentAnswer?.studentScore || 0} / ${question.questionScore}分</span>
          </div>

          <div class="question-content">
            <div class="question-title">${question.questionContent}</div>

            // ${question.options ? `
            //   <div class="question-options">
            //     ${question.options.map(opt => `
            //       <div class="option ${opt.isCorrect ? 'correct-option' : ''} ${studentAnswer?.studentAnswer === opt.optionId ? (opt.isCorrect ? 'correct-selected' : 'incorrect-selected') : ''}">
            //         ${opt.content}
            //       </div>
            //     `).join('')}
            //   </div>
            // ` : ''}

            ${studentAnswer ? `
              <div class="student-answer">
                <label>你的答案：</label>
                <span>${studentAnswer.studentAnswer || '未作答'}</span>
              </div>
            ` : ''}

            <div class="correct-answer">
              <label>正确答案：</label>
              <span>${question.questionAnswer}</span>
            </div>
          </div>
        </div>
      `;
      }).join('')}
  </div>
` : `
  <div class="report-section">
    <h2><i class="fas fa-info-circle"></i> 等待批改</h2>
    <div class="info-panel">
      该练习已提交，等待教师批改。批改完成后可查看详细题目分析。
    </div>
  </div>
`}

          <div class="report-footer">
            <div class="footer-info">
              报告生成时间：${new Date().toLocaleString()}
            </div>
          </div>
        </div>
      `;
    }
  }
};
</script>

<style scoped>
/* 导入公共样式 */
@import '../../assets/css/exercise_css/ExerciseCommon.css';

/* 筛选区域样式 */
.filter-section {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.filter-dropdown {
  padding: 0.4rem 0.8rem;
  border: 1px solid #e4e7eb;
  border-radius: 4px;
  font-size: 0.9rem;
}

/* 卡片样式调整 */
.exercise-card {
  border: 1px solid #e1e4e8;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 2px 5px rgba(0,0,0,0.05);
  transition: transform 0.2s, box-shadow 0.2s;
}

.exercise-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(0,0,0,0.08);
}

.card-title {
  font-weight: 600;
  color: #333;
}

.card-text {
  color: #666;
  line-height: 1.6;
}

/* 状态标签 */
.status-badge {
  padding: 0.25rem 0.75rem;
  border-radius: 12px;
  font-size: 0.8rem;
  font-weight: 500;
}


/* 按钮样式 */
.btn {
  padding: 0.5rem 1rem;
  border-radius: 6px;
  font-size: 0.9rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  border: none;
}

.btn-primary {
  background: #3b82f6;
  color: white;
}

.btn-primary:hover {
  background: #2563eb;
}

.btn-secondary {
  background: #f3f4f6;
  color: #4b5563;
  border: 1px solid #e5e7eb;
}

.btn-secondary:hover {
  background: #e5e7eb;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .filter-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
  }

  .exercise-grid {
    grid-template-columns: 1fr;
  }

  .btn {
    width: 100%;
    margin-top: 0.5rem;
    justify-content: center;
  }

  .btn-export {
    margin-left: 0.5rem;
  }
}

/* 隐藏的报告容器 */
.report-container {
  position: absolute;
  left: -9999px;
  top: -9999px;
}

.hidden {
  display: none;
}
</style>

<style>
/* 报告样式 - 全局生效 */
.report {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  width: 210mm;
  min-height: 297mm;
  padding: 15mm;
  margin: 0 auto;
  box-sizing: border-box;
  background-color: #fff;
  color: #333;
  box-shadow: 0 0 10px rgba(0,0,0,0.1);
}

.report-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.report-logo {
  width: 60px;
  height: 60px;
  background: #4f46e5;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.report-logo i {
  font-size: 30px;
  color: white;
}

.report-title h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #1e293b;
}

.report-subtitle {
  font-size: 16px;
  color: #64748b;
  margin-top: 5px;
}

.report-summary {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30px;
  padding: 15px;
  background: #f8fafc;
  border-radius: 8px;
  border-left: 4px solid #4f46e5;
}

.summary-item {
  text-align: center;
}

.summary-label {
  font-size: 14px;
  color: #64748b;
  margin-bottom: 5px;
}

.summary-value {
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
}

.score-value {
  color: #10b981;
  font-size: 22px;
}

.score-percent {
  font-size: 14px;
  color: #64748b;
}

.report-section {
  margin-bottom: 30px;
}

.report-section h2 {
  font-size: 18px;
  font-weight: 600;
  color: #334155;
  padding-bottom: 8px;
  border-bottom: 1px solid #e2e8f0;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.report-section h2 i {
  margin-right: 8px;
  color: #4f46e5;
}

.exercise-info {
  width: 100%;
  border-collapse: collapse;
}

.exercise-info td {
  padding: 8px 12px;
  border-bottom: 1px solid #e2e8f0;
}

.exercise-info td:first-child {
  font-weight: 500;
  width: 120px;
  color: #475569;
}

.question-item {
  margin-bottom: 20px;
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #4f46e5;
  background: #f8fafc;
}

.question-item.correct {
  border-left-color: #10b981;
}

.question-item.incorrect {
  border-left-color: #ef4444;
}

.question-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  padding-bottom: 8px;
  border-bottom: 1px dashed #cbd5e1;
}

.question-number {
  font-weight: 500;
  color: #1e293b;
}

.question-score {
  font-weight: 600;
  color: #4f46e5;
}

.question-title {
  margin-bottom: 10px;
  font-size: 16px;
  line-height: 1.5;
}

.question-options {
  margin-bottom: 10px;
}

.option {
  padding: 8px 12px;
  margin-bottom: 5px;
  border-radius: 6px;
  background: #e2e8f0;
  border: 1px solid #cbd5e1;
}

.correct-option {
  background: #dcfce7;
  border-color: #86efac;
}

.correct-selected {
  background: #10b981 !important;
  color: white !important;
  border-color: #059669 !important;
}

.incorrect-selected {
  background: #fecaca !important;
  border-color: #fca5a5 !important;
}

.student-answer, .correct-answer {
  margin-top: 8px;
  padding: 8px;
  border-radius: 6px;
}

.student-answer {
  background: #dbeafe;
}

.correct-answer {
  background: #ecfdf5;
}

.student-answer label, .correct-answer label {
  font-weight: 500;
  color: #4b5563;
}

.info-panel {
  padding: 20px;
  text-align: center;
  background: #f8fafc;
  border-radius: 8px;
  color: #64748b;
  font-size: 16px;
}

.report-footer {
  margin-top: 40px;
  padding-top: 20px;
  border-top: 1px solid #eee;
  font-size: 14px;
  color: #64748b;
}

.footer-signature {
  margin-top: 40px;
  width: 200px;
}

.signature-line {
  border-bottom: 1px solid #cbd5e1;
  margin-bottom: 5px;
  height: 30px;
}

.signature-label {
  text-align: center;
  color: #64748b;
}
</style>
